<?php
namespace app\admin\controller;
use think\Controller;
/*
 * 销售部岗位绩效考核 
 * 
*/
class AssessmentSalesman extends Controller
{
    public function assessmentList()
    {
        if(input('limit'))
        {
            $list = db('salesman_assessment');
            if(input('keywords'))
                $list = $list->where('item_name','LIKE',"%".input('keywords')."%");
            $list = $list->where('status','1')->order('id DESC')->select();
            return ['code'=>0,'count'=>count($list),'data'=>$list,'msg'=>''];
        }
        return view();
    }
    
    public function assessmentAdd()
    {
        $id = input('id');
        if(request()->isAjax())
        {
            $data=input('post.');
            if($id)
            {
                db('salesman_assessment')->where('id',$id)->update($data);
            }
            else 
            {
                $data['job_ids'] = implode(',',$data['job_id']);
                $data['job_names'] = db('sale_dept_job')->where('id','IN',$data['job_ids'])->order('id ASC')->value('GROUP_CONCAT(name)');
                $data['year'] = explode('-',$data['date'])[0];
                $data['month'] = explode('-',$data['date'])[1];
                $data['create_time'] = time();
                db('salesman_assessment')->insert($data);
            }
            return ['msg'=>'操作成功','icon'=>1];
        }
        $this->assign([
            'jobList'=>db('sale_dept_job')->order('id ASC')->select(),
            'data'=>db('salesman_assessment')->where('id',$id)->find(),
        ]);
        return view();
    }
    
    public function itemList()
    {
        if(input('limit'))
        {
            $jobId = input('job_id');
            $admin_id = session('uid','','admin');
            $list = db('salesman_assessment_item');
            if($jobId)
                 $list = $list->where('job_id',$jobId);
            if(input('keywords'))
                $list = $list->where('item_name','LIKE',"%".input('keywords')."%");
            $list = $list->order('job_id ASC,sort ASC,id ASC')->select();
    
            return ['code'=>0,'count'=>count($list),'data'=>$list,'msg'=>''];
        }
        $jobList = db('sale_dept_job')->order('id ASC')->select();
        foreach ($jobList as $k=>$v)
        {
            $jobList[$k]['count'] = db('admin')->where('job_id',$v['id'])->where('status',1)->count();
            $jobList[$k]['sum'] = intval(db('salesman_assessment_item')->where('job_id',$v['id'])->where('status',1)->value('sum(max_score)'));
        }
        $this->assign([
            'jobList'=>$jobList,
        ]);
        return view();
    }
    
    
    public function itemEdit()
    {
        $id = input('id');
        if(request()->isAjax())
        {
            $data=input('post.');
            if($id)
            {
                db('salesman_assessment_item')->where('id',$id)->update($data);
            }
            else 
            {
                $data['status'] = 1;
                $data['create_time'] = time();
                db('salesman_assessment_item')->insert($data);
            }
            return ['msg'=>'操作成功','icon'=>1];
        }
        $this->assign([
            'jobList'=>db('sale_dept_job')->order('id ASC')->select(),
            'data'=>db('salesman_assessment_item')->where('id',$id)->find(),
        ]);
        return view();
    }
    
    public function scoreResult()
    {
        if(input('limit'))
        {
            $assessmentId = input('assessment_id');
            $adminId = session('uid','','admin');
            $groupId =  session('group_id','','admin');
            $departmentId =  session('department_id','','admin');
            $list = db('salesman_assessment_result')->alias('a');
            if($assessmentId)
                $list = $list->where('a.assessment_id',$assessmentId);
            //初始化
            if($list->count() == 0)
            {
                $assessmentInfo = db('salesman_assessment')->where('id',$assessmentId)->find();
                $adminList = db('admin')->where('job_id','IN',$assessmentInfo['job_ids'])->where('department_id','>',0)->where('status',1)->select();
                foreach($adminList as $k=>$v)
                {
                    db('salesman_assessment_result')->insert(['assessment_id'=>$assessmentId,'job_id'=>$v['job_id'],'admin_id'=>$v['id']]);
                }
            }
            $list = db('salesman_assessment_result')->alias('a')->where('a.assessment_id',$assessmentId);
            $list = $list->field('a.*,b.department_id,b.group_id,b.name as admin_name,c.name as job_name,b.parent_id')->join('admin b','a.admin_id = b.id')->join('sale_dept_job c','a.job_id = c.id');
            if(input('keywords'))
                $list = $list->where('b.name','LIKE',"%".input('keywords')."%");
            if(input('job_id'))
                $list = $list->where('a.job_id',input('job_id'));
            if(input('department_id'))
                $list = $list->where('b.department_id',input('department_id'));
            //部门主管
            if($groupId == 5)
                $list = $list->where('b.department_id',$departmentId);
            //营销
            if($groupId == 2)
                $list = $list->where("b.parent_id = {$adminId} OR b.id = {$adminId}");
            $list = $list->order('b.department_id ASC,a.job_id DESC,a.admin_id ASC,a.id ASC')->select();
            foreach ($list as $k=>$v)
            {
                if($v['scoring_admin_id'])
                    $list[$k]['scoring_admin_name'] = db('admin')->where('id',$v['scoring_admin_id'])->value('name');
                if($groupId == 1)
                {
                    $list[$k]['can_view'] = 1;
                    $list[$k]['can_scoring'] = 1;
                    $list[$k]['can_del'] = 1;
                }//营销权限
                else if($groupId == 2)
                {
                    if($v['admin_id'] == $adminId || $v['parent_id'] == $adminId)
                    {
                        $list[$k]['can_view'] = 1;
                        $list[$k]['can_scoring'] = 1;
                    }
                }//主管权限
                else if($groupId == 5)
                {
                    if($v['department_id'] == $departmentId && $v['group_id'] == 2 || $v['admin_id'] == $adminId)
                    {
                        $list[$k]['can_view'] = 1;
                        $list[$k]['can_scoring'] = 1;
                    }
                }
                if($v['merit_pay'] &&  $v['final_score'] && $v['max_score'])
                    $list[$k]['final_merit_pay'] = $v['merit_pay'] * $v['final_score'] / $v['max_score'];
                //can_view can_scoring can_del
            }
            return ['code'=>0,'count'=>count($list),'data'=>$list,'msg'=>''];
        }
        $jobList = db('sale_dept_job')->order('id ASC')->select();
        foreach ($jobList as $k=>$v)
        {
            $jobList[$k]['count'] = db('admin')->where('job_id',$v['id'])->where('status',1)->count();
        }
        $this->assign([
            'jobList'=>$jobList,
        ]);
        return view();
    }

    public function scoreList()
    {
        if(input('limit'))
        {
            $id = input('id');
            $adminId = input('admin_id');
            $check = db('salesman_assessment_score')->where('assessment_id',$id)->where('admin_id',$adminId)->count();
            //初始化
            if(!$check)
            {
                $itemList = db('salesman_assessment_item')->where('job_id',input('job_id'))->order('sort ASC,id ASC')->select();
                foreach ($itemList as $k=>$v)
                {
                    db('salesman_assessment_score')->insert(['assessment_id'=>$id,'admin_id'=>$adminId,'item_id'=>$v['id'],]);
                }
            }
            $list = db('salesman_assessment_score')->alias('a')->field('a.*,b.*')->join('salesman_assessment_item b','a.item_id = b.id')->where('a.assessment_id',$id)->where('a.admin_id',$adminId)->order('b.sort ASC')->select();
            return ['code'=>0,'count'=>count($list),'data'=>$list,'msg'=>''];
        }
        $data = db('salesman_assessment')->where('id',input('id'))->find();
        $time1 = strtotime("{$data['year']}-{$data['month']}-01");
        $time2 = strtotime("{$data['year']}-{$data['month']}-01 +1 month");
        $this->assign([
            'result' => db('salesman_assessment_result')->where('assessment_id',input('id'))->where('admin_id',input('admin_id'))->find(),
            'typeCheck' => db('salesman_assessment_item')->where('job_id',input('job_id'))->where('type_name','<>','')->count(),
            'clientCount' => db('client')->where('aid',input('admin_id'))->whereBetween('add_time',[ $time1,$time2 ]  )->count(),
            'qdCount'  => db('client')->where('xaid',input('admin_id'))->where('status',4)->whereBetween('qiandan_time',[ $time1,$time2 ]  )->count(),
            'performanceData' => db('performance')->field('count(*) as count, sum(salesman_final_performance) as sum')->where('admin_id',input('admin_id'))->whereBetween('end_date',[ $time1,$time2 ]  )->find(),
        ]);
        return view();
    }
    
    public function scoring()
    {
        $id = input('id');
        $adminId = input('admin_id');
        $data = db('salesman_assessment')->where('id',input('id'))->find();
        if(input('post.'))
        {
            $data = input('post.');
            if($data['self_score'])
            {
                foreach ($data['self_score'] as $k=>$v)
                {
                    if($v == '')
                    {
                        return ['msg'=>'操作失败，有未填项','icon'=>2];
                    }
                }
                $finaScore =  0;
                foreach ($data['self_score'] as $k=>$v)
                {
                    db('salesman_assessment_score')->where('id',$k)->update(['self_score'=>$v ]);
                    $finaScore += $v;
                }
                db('salesman_assessment_result')->where('id',$data['result_id'])->update([
                    'self_score'=>$finaScore,
                    'max_score'=>$data['max_score'],
                ]);
            }
            if($data['final_score'])
            {
                if($data['merit_pay'] == '') return ['msg'=>'操作失败，有未填项','icon'=>2];
                foreach ($data['final_score'] as $k=>$v)
                {
                    if($v == '')
                    {
                        return ['msg'=>'操作失败，有未填项','icon'=>2];
                    }
                }
                $finaScore =  0;
                foreach ($data['final_score'] as $k=>$v)
                {
                    db('salesman_assessment_score')->where('id',$k)->update(['final_score'=>$v,'scoring_admin_id'=> session('uid','','admin') ]);
                    $finaScore += $v;
                }
                db('salesman_assessment_result')->where('id',$data['result_id'])->update([
                    'merit_pay'=>$data['merit_pay'],
                    'final_score'=>$finaScore,
                    'max_score'=>$data['max_score'],
                    'scoring_admin_id'=>session('uid','','admin'),
                ]);
            }
            return ['msg'=>'操作成功','icon'=>1];
        }
        $time1 = strtotime("{$data['year']}-{$data['month']}-01");
        $time2 = strtotime("{$data['year']}-{$data['month']}-01 +1 month");
        
        $check = db('salesman_assessment_score')->where('assessment_id',$id)->where('admin_id',$adminId)->count();
        //初始化
        if(!$check)
        {
            $itemList = db('salesman_assessment_item')->where('job_id',input('job_id'))->order('sort ASC,id ASC')->select();
            foreach ($itemList as $k=>$v)
            {
                db('salesman_assessment_score')->insert(['assessment_id'=>$id,'admin_id'=>$adminId,'item_id'=>$v['id'],'max_score'=>$v['max_score']]);
            }
        }
        $list = db('salesman_assessment_score')->alias('a')->field('a.*,b.item_name,b.type_name,b.max_score,b.index_desc,b.rule_desc')->join('salesman_assessment_item b','a.item_id = b.id')->where('a.assessment_id',$id)->where('a.admin_id',$adminId)->order('b.sort ASC')->select();
        $this->assign([
            'itemList' => $list,
            'result' => db('salesman_assessment_result')->where('assessment_id',$id)->where('admin_id',$adminId)->find(),
            'typeCheck' => db('salesman_assessment_item')->where('job_id',input('job_id'))->where('type_name','<>','')->count(),
            'clientCount' => db('client')->where('aid',input('admin_id'))->whereBetween('add_time',[ $time1,$time2 ]  )->count(),
            'qdCount'  => db('client')->where('xaid',input('admin_id'))->where('status',4)->whereBetween('qiandan_time',[ $time1,$time2 ]  )->count(),
            'performanceData' => db('performance')->field('count(*) as count, sum(salesman_final_performance) as sum')->where('admin_id',input('admin_id'))->whereBetween('end_date',[ $time1,$time2 ]  )->find(),
        ]);
        //营销、主管
        if(input('job_id') < 6 )
        {
            $adminInfo = db('admin')->where('id',$adminId)->find();
            if(session('group_id','','admin') == 2 && $adminId == session('uid','','admin') )
            {
                $this->assign('selfOn',1);
            }
            else if( session('group_id','','admin') == 1
                || (session('group_id','','admin') == 5 && session('department_id','','admin') == $adminInfo['department_id'])
                || session('uid','','admin') == $adminInfo['parent_id'] )
            {
                //$this->assign('selfOn',1);
                $this->assign('finaOn',1);
            }
        }
        else
        {
            if(session('group_id','','admin') == 5 && $adminId == session('uid','','admin') )
            {
                $this->assign('selfOn',1);
            }
            else if(session('group_id','','admin') == 1)
            {
                //$this->assign('selfOn',1);
                $this->assign('finaOn',1);
            }
        }
        return view();
    }
    
    
}